package com.cssw.fyzb.busi.api.acct;

import com.cssw.fyzb.busi.service.acct.AcctService;
import com.cssw.fyzb.busi.service.pay.PayService;
import com.cssw.fyzb.busi.util.Const;
import com.cssw.fyzb.busi.util.NumberUtil;
import com.cssw.fyzb.core.dao.system.SysParamDao;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.dodb.*;
import com.cssw.fyzb.core.util.StringUtil;
import com.ijpay.core.kit.PayKit;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Author zhouxu
 * @create 2020-12-18 20:57
 */
@Function(description = "购买福币", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户ID", required = true),
        @Parameter(name = "payWay", type = Type.String, description = "支付方式（1微信 2支付宝）", required = true),
        @Parameter(name = "type", type = Type.String, description = "1.指定金额 2.其他金额", required = true),
        @Parameter(name = "rfId", type = Type.Integer, description = "固定金额ID", required = false),
        @Parameter(name = "num", type = Type.Decimal, description = "数量", required = false),
        @Parameter(name = "expend", type = Type.Decimal, description = "微信支付的json参数（{open_id: ''}）", required = false),
})
@Component
public class BuyFCoin implements Action {

    private static final Logger logger = LoggerFactory.getLogger(BuyFCoin.class);
    @Autowired
    private PayService payService;
    @Autowired
    private AcctService acctService;
    @Autowired
    private SysParamDao sysParamDao;

    public static final String TYPE_1 = "1";

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        String payWay = request.getString("payWay");
        String type = request.getString("type");

        Integer amount = null;
        BigDecimal fCoinNum = null;
        if (TYPE_1.equals(type)) {
            // 指定金额，走系统参数
            Long rfId = request.getLong("rfId");
            RnbExchangeFDef def = acctService.findRnbBuyFDef(rfId);
            if (def == null) {
                return Response.fail("参数异常");
            }
            amount = def.getRnb()
                    .multiply(BigDecimal.valueOf(100))
                    .intValue();

            fCoinNum = def.getFCoin().setScale(2);

        } else {
            if (StringUtil.isEmpty(request.getString("num"))){
                return Response.fail("必须输入购买数量");
            }

            // 其他金额
            BigDecimal bigNnum = new BigDecimal(request.getString("num"));
            if (!NumberUtil.isWholeNumber(bigNnum)){
                return Response.fail("购买数量必须是整数");
            }

            int limitNum = Integer.parseInt(sysParamDao.findByCode(SysParam.BUY_F_COIN_MIN_NUM).getParamValue());
            if (bigNnum.intValue() < limitNum) {
                return Response.fail("购买数量不能小于" + limitNum);
            }
            
            BigDecimal rate = new BigDecimal(sysParamDao.findByCode(Const.RNB_F_RATE).getParamValue());
            amount = bigNnum
                    .multiply(rate)
                    .multiply(BigDecimal.valueOf(100))
                    .intValue();

            fCoinNum = bigNnum.setScale(2);

        }

        // 随机订单号
        String outTradeNo = PayKit.generateStr();
        try {
            acctService.saveRnbExchangeCoinLog(userId, new BigDecimal(amount), AcctType.ACCT_TYPE_F,
                    fCoinNum, outTradeNo, RnbExchangeCoinLog.STATUS_INIT, request.getString("expend"));

            if (PayOrder.PAY_WECHAT.equals(payWay)) {
                // 生成订单
                PayOrder order = payService.createPayOrder(userId, amount, PayOrder.PAY_BUSI_BUY_F_COIN, outTradeNo, payWay, fCoinNum);
                //  调起第三方支付
//                return payService.wxPay(order);
                return payService.wxAdapay(order, "购买福币", "购买福币，数量" + fCoinNum, request.getString("expend"));
            } else if (PayOrder.PAY_Ali.equals(payWay)) {
                // 生成订单
                PayOrder order = payService.createPayOrder(userId, amount, PayOrder.PAY_BUSI_BUY_F_COIN, outTradeNo, payWay, fCoinNum);
                //  调起第三方支付
//                return payService.aliPay(order);
                return payService.aliAdapay(order, "购买福币", "购买福币，数量" + fCoinNum);
            } else {
                return Response.fail("不支持该交易方式");
            }
        } catch (BizException e) {
            logger.error(e.getErrMsg(), e.getErrCode());
            return Response.fail(e.getMessage(), e.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail(e);
        }


    }
}
